package com.dify.knowledge.service;

import com.dify.knowledge.exception.DifyApiException;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataSet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * SOP生成服务
 */
@Slf4j
@Service
public class SopService {

    private final DifyService difyService;

    public SopService(DifyService difyService) {
        this.difyService = difyService;
    }

    /**
     * 生成SOP内容
     * 
     * @param topic SOP主题
     * @return SOP内容
     */
    public String generateSopContent(String topic) {
        log.info("生成SOP内容，主题：{}", topic);
        
        try {
            String content = difyService.generateSop(topic);
            
            // 检查是否包含"无相关知识"的提示
            if (content.contains("没有相关内容") || content.contains("无相关知识") || 
                content.contains("无法找到") || content.contains("知识库中没有")) {
                log.warn("知识库中没有关于主题'{}'的相关内容", topic);
                return null;
            }
            
            // 添加生成时间标注
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String sopWithMetadata = "# " + topic + " - 标准操作流程\n\n" +
                                    "**生成时间：** " + timestamp + "\n\n" +
                                    "---\n\n" +
                                    content;
            
            log.info("SOP内容生成成功");
            return sopWithMetadata;
            
        } catch (DifyApiException e) {
            log.error("生成SOP内容失败", e);
            throw e;
        }
    }

    /**
     * 将内容转换为PDF
     * 使用 flexmark-java 解析 Markdown，openhtmltopdf 生成 PDF
     * 
     * @param content Markdown格式的文本内容
     * @return PDF字节数组
     */
    public byte[] convertToPdf(String content) {
        log.info("将Markdown内容转换为PDF");
        
        try {
            // 1. 配置 Flexmark 解析器
            MutableDataSet options = new MutableDataSet();
            Parser parser = Parser.builder(options).build();
            HtmlRenderer renderer = HtmlRenderer.builder(options).build();
            
            // 2. 将 Markdown 转换为 HTML
            Node document = parser.parse(content);
            String htmlBody = renderer.render(document);
            
            // 3. 构建完整的 HTML 文档（包含 CSS 样式）
            String htmlDocument = buildHtmlDocument(htmlBody);
            
            // 4. 使用 OpenHTMLtoPDF 将 HTML 转换为 PDF，配置中文字体
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                PdfRendererBuilder builder = new PdfRendererBuilder();
                builder.useFastMode();
                builder.withHtmlContent(htmlDocument, null);
                
                // 加载中文字体
                loadChineseFont(builder);
                
                builder.toStream(outputStream);
                builder.run();
                
                log.info("PDF转换成功");
                return outputStream.toByteArray();
            }
            
        } catch (Exception e) {
            log.error("PDF转换失败", e);
            throw new RuntimeException("PDF转换失败：" + e.getMessage(), e);
        }
    }
    
    /**
     * 加载中文字体
     * 尝试从多个位置加载中文字体以支持中文显示
     */
    private void loadChineseFont(PdfRendererBuilder builder) {
        String[] fontPaths = {
            // 项目资源字体
            "fonts/SystemFont.ttc",
            "fonts/NotoSansSC-Regular.otf",
            "fonts/NotoSansSC-Regular.ttf",
            "fonts/SimSun.ttf",
            "fonts/SimHei.ttf",
            
            // macOS 系统字体
            "/System/Library/Fonts/PingFang.ttc",
            "/System/Library/Fonts/STHeiti Light.ttc",
            "/System/Library/Fonts/Supplemental/Songti.ttc",
            "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
            
            // Linux 系统字体
            "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
            "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
            "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
            
            // Windows 系统字体
            "C:/Windows/Fonts/simhei.ttf",
            "C:/Windows/Fonts/simsun.ttc",
            "C:/Windows/Fonts/msyh.ttc"
        };
        
        boolean fontLoaded = false;
        
        for (String fontPath : fontPaths) {
            try {
                if (fontPath.startsWith("fonts/")) {
                    // 尝试从项目资源加载
                    ClassPathResource resource = new ClassPathResource(fontPath);
                    log.info("检查资源字体: {} - 存在: {}", fontPath, resource.exists());
                    
                    if (resource.exists()) {
                        // 创建临时文件来避免InputStream关闭问题
                        File tempFile = File.createTempFile("font", ".ttc");
                        tempFile.deleteOnExit();
                        
                        try (InputStream fontStream = resource.getInputStream()) {
                            java.nio.file.Files.copy(fontStream, tempFile.toPath(), 
                                java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                        }
                        
                        builder.useFont(tempFile, "ChineseFont");
                        log.info("✓ 成功加载项目资源字体: {} (大小: {} KB)", 
                            fontPath, tempFile.length() / 1024);
                        fontLoaded = true;
                        break;
                    }
                } else {
                    // 尝试从系统路径加载
                    File fontFile = new File(fontPath);
                    log.debug("检查系统字体: {} - 存在: {}, 可读: {}", 
                        fontPath, fontFile.exists(), fontFile.canRead());
                    
                    if (fontFile.exists() && fontFile.canRead()) {
                        builder.useFont(fontFile, "ChineseFont");
                        log.info("✓ 成功加载系统字体: {} (大小: {} KB)", 
                            fontPath, fontFile.length() / 1024);
                        fontLoaded = true;
                        break;
                    }
                }
            } catch (Exception e) {
                log.warn("加载字体失败 {}: {}", fontPath, e.getMessage());
            }
        }
        
        if (!fontLoaded) {
            log.error("❌ 未能加载任何中文字体，PDF中的中文将显示为乱码");
            log.error("当前字体搜索路径:");
            for (String path : fontPaths) {
                if (path.startsWith("fonts/")) {
                    ClassPathResource resource = new ClassPathResource(path);
                    log.error("  {} - 存在: {}", path, resource.exists());
                } else {
                    File file = new File(path);
                    log.error("  {} - 存在: {}", path, file.exists());
                }
            }
            log.error("解决方案:");
            log.error("1. 运行 ./download-chinese-font.sh 下载字体到项目");
            log.error("2. 重新编译并重启应用");
            log.error("3. 检查 src/main/resources/fonts/ 目录是否有字体文件");
        }
    }
    
    /**
     * 构建完整的 HTML 文档，包含 CSS 样式
     */
    private String buildHtmlDocument(String htmlBody) {
        return """
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8"/>
                <style>
                    @page {
                        size: A4;
                        margin: 2cm;
                    }
                    
                    body {
                        font-family: "ChineseFont", "SimSun", "Microsoft YaHei", "PingFang SC", sans-serif;
                        font-size: 12pt;
                        line-height: 1.6;
                        color: #333;
                    }
                    
                    h1 {
                        font-size: 24pt;
                        font-weight: bold;
                        margin-top: 0.5em;
                        margin-bottom: 0.5em;
                        color: #000;
                        border-bottom: 2px solid #333;
                        padding-bottom: 0.3em;
                    }
                    
                    h2 {
                        font-size: 20pt;
                        font-weight: bold;
                        margin-top: 0.8em;
                        margin-bottom: 0.4em;
                        color: #000;
                    }
                    
                    h3 {
                        font-size: 16pt;
                        font-weight: bold;
                        margin-top: 0.6em;
                        margin-bottom: 0.3em;
                        color: #000;
                    }
                    
                    h4, h5, h6 {
                        font-size: 14pt;
                        font-weight: bold;
                        margin-top: 0.5em;
                        margin-bottom: 0.3em;
                        color: #000;
                    }
                    
                    p {
                        margin: 0.5em 0;
                        text-align: justify;
                    }
                    
                    strong, b {
                        font-weight: bold;
                        color: #000;
                    }
                    
                    em, i {
                        font-style: italic;
                    }
                    
                    ul, ol {
                        margin: 0.5em 0;
                        padding-left: 2em;
                    }
                    
                    li {
                        margin: 0.3em 0;
                    }
                    
                    hr {
                        border: none;
                        border-top: 1px solid #ccc;
                        margin: 1em 0;
                    }
                    
                    code {
                        font-family: "Courier New", monospace;
                        background-color: #f5f5f5;
                        padding: 0.2em 0.4em;
                        border-radius: 3px;
                        font-size: 0.9em;
                    }
                    
                    pre {
                        background-color: #f5f5f5;
                        padding: 1em;
                        border-radius: 5px;
                        overflow-x: auto;
                        margin: 1em 0;
                    }
                    
                    pre code {
                        background-color: transparent;
                        padding: 0;
                    }
                    
                    blockquote {
                        border-left: 4px solid #ddd;
                        padding-left: 1em;
                        margin: 1em 0;
                        color: #666;
                    }
                    
                    table {
                        border-collapse: collapse;
                        width: 100%%;
                        margin: 1em 0;
                    }
                    
                    th, td {
                        border: 1px solid #ddd;
                        padding: 0.5em;
                        text-align: left;
                    }
                    
                    th {
                        background-color: #f5f5f5;
                        font-weight: bold;
                    }
                </style>
            </head>
            <body>
                %s
            </body>
            </html>
            """.formatted(htmlBody);
    }

    /**
     * 格式化为Markdown
     * 
     * @param content 原始内容
     * @return Markdown格式内容
     */
    public String convertToMarkdown(String content) {
        log.info("格式化为Markdown");
        
        // 内容已经是Markdown格式，直接返回
        // 可以在这里添加额外的格式化逻辑
        return content;
    }
}
